# -*- coding:utf-8 -*-

import binascii, datetime, random
from twisted.python import log
from twisted.internet import reactor, task
from twisted.internet.protocol import ServerFactory, Protocol


# fan protocol
class protocol(Protocol):
    def __init__(self):
        pass

    def send_Data(self, data):
        log.msg('[%s], send command: %s' % (self.transport.getPeer(), data))
        log.msg('-----------------request end-----------------------\n')
        self.transport.write(data)

    def connectionMade(self):
        log.msg('User [ %s ], has been connection' % self.transport.getPeer())
        # self.send_Data("[{'user': '123', 'password': '321'}, {'user': '773', 'password': '881'}]")

    def connectionLost(self, reason):
        log.msg("[%s] connection lost." % (self.transport.getPeer()))

    def dataReceived(self, data):
        log.msg(data)
        for each in xrange(3):
            self.send_Data("[{'user': '%s', 'password': '%s'}, {'user': '%s', 'password': '%s'}]" % (random.randint(0, 1000), random.randint(0, 1000), random.randint(0, 1000), random.randint(0, 1000)))
        self.send_Data("over")


class factory(ServerFactory):
    protocol = protocol

    def __init__(self):
        pass

    def connectionLost(self):
        log.msg('Connection lost')


def main():
    parm = {'tcpPort': 12345,
            'serviceIface': '',
            'redisParm': ('127.0.0.1', 6379, 0),
            'mysqlDBParm': ('192.168.1.5', 3306, 'root', 'w111111', 'test'),
            'mongoDBUri': 'mongodb://127.0.0.1'}

    log.startLogging(open(r"testLog.log", 'w'))  # log
    # Service for fan
    fac = factory()  # Protocol factory

    reactor.listenTCP(parm['tcpPort'], fac, interface=parm['serviceIface'])
    log.msg('----------The warehouse Service begin now...----------')
    reactor.run()

if __name__ == "__main__":
    main()
